package cn.geminis.lowcode.compiler.code;

import cn.geminis.lowcode.compiler.util.JdkTreeMakerUtils;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ExpressionTree;
import lombok.Getter;

import javax.lang.model.element.Element;
import java.util.ArrayList;
import java.util.Map;
import java.util.Objects;

/**
 * @author puddi
 */
@Getter
public class LcAnnotation extends AbstractCode<AnnotationTree, Element> {

    private final String type;
    private final Map<String, Object> args;

    public LcAnnotation(String type) {
        this.type = type;
        this.args = Map.of();
    }

    public LcAnnotation(String type, Map<String, Object> args) {
        this.type = type;
        this.args = args;
    }


    @Override
    protected AnnotationTree createJdkTree() {
        var argTrees = new ArrayList<ExpressionTree>();
        for (var arg : args.entrySet()) {
            if (Objects.isNull(arg.getKey()) || arg.getKey().isEmpty()) {
                argTrees.add(arg.getValue() instanceof ExpressionTree ? (ExpressionTree) arg.getValue() : JdkTreeMakerUtils.literal(arg.getValue()));
            } else {
                argTrees.add(
                        JdkTreeMakerUtils.assign(
                                JdkTreeMakerUtils.select(arg.getKey()),
                                arg.getValue() instanceof ExpressionTree ? (ExpressionTree) arg.getValue() : JdkTreeMakerUtils.literal(arg.getValue())
                        )
                );
            }
        }

        return JdkTreeMakerUtils.annotation(this.type, argTrees);
    }

    @Override
    protected Element createJdkElement() {
        return null;
    }
}
